package com.zt.rongda.workbill.service;

import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.rongda.ad.inter.AdDesignMapper;
import com.zt.rongda.ad.model.AdDesign;
import com.zt.rongda.constant.BusConstant;
import com.zt.rongda.order.inter.OrderItemMapper;
import com.zt.rongda.order.model.OrderItem;
import com.zt.rongda.workbill.inter.WorkBillMapper;
import com.zt.rongda.workbill.inter.WorkbillItemMapper;
import com.zt.rongda.workbill.inter.WorkbillTaskMapper;
import com.zt.rongda.workbill.model.WorkBill;
import com.zt.rongda.workbill.model.WorkbillItem;
import com.zt.rongda.workbill.model.WorkbillTask;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.StringUtil;

@Service
public class WorkBillService extends BaseService {

    @Autowired
    private WorkBillMapper workBillMapper;
    
    @Autowired
    private WorkbillTaskMapper workbillTaskMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private AdDesignMapper adDesignMapper;
    
    @Autowired
    private WorkbillItemMapper workbillItemMapper;
    
    


    /**
    * 查询
    *
    * @param reqBean
    * @return
    */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("select w.*, o.CUSTOMER_ID  ");
        sqlBuilder.appendSql("from AD_WORKBILL w, AD_ORDER o where w.ORDER_ID = o.ORDER_ID ");
        sqlBuilder.addWhere("w.WORKBILL_ID", reqBean.getInfo("workbillId"));
        sqlBuilder.addWhere("o.ORDER_ID", reqBean.getInfo("orderId"));
        sqlBuilder.addWhere("o.CUSTOMER_ID", reqBean.getInfo("customerId"));
        sqlBuilder.addWhere("o.C_ORDER_TYPE", reqBean.getInfo("orderType"));
        sqlBuilder.addWhere("w.C_WORKBILL_TYPE", reqBean.getInfo("workbillType"));
        sqlBuilder.addWhere("w.STATUS", reqBean.getInfo("status"));
        sqlBuilder.orderBy(" order by MAKE_TIME DESC");
        JSONObject result = queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
        if(result != null){
            JSONArray rows = result.getJSONArray("rows");
            for(Object o : rows){
                JSONObject workbill = (JSONObject)o;
                workbill.put("workbillItems", getWorkbillItems(workbill.optString("workbillId")));
            }
        }
        return result;
    }
    
    /**
     * 查询工单列表
     * @param orderId
     * @return
     */
    public JSONArray getWorkBills(String orderId){
        SqlBuilder sqlBuilder = new SqlBuilder("select * from AD_WORKBILL where ORDER_ID = '" + orderId + "'");
        sqlBuilder.orderBy(" ORDER BY MAKE_TIME DESC ");
        JSONArray workbills = query(sqlBuilder);
        if(workbills != null){
            for(Object o : workbills){
                JSONObject workbill = (JSONObject)o;
                workbill.put("workbillItems", getWorkbillItems(workbill.optString("workbillId")));
            }
        }
        return workbills;
    }
    
    public JSONArray getWorkbillItems(String workbillId){
        StringBuffer sql = new StringBuffer("select * from AD_WORKBILL_ITEM wi ");
        sql.append(" where wi.WORKBILL_ID = ? ");
        sql.append(" order by wi.MAKE_TIME");
        JSONArray workbillItems = query(sql.toString(),workbillId);
        if(workbillItems != null){
            for(Object o : workbillItems){
                JSONObject workbillItem = (JSONObject)o;
                OrderItem orderItem = orderItemMapper.selectByPrimaryKey(workbillItem.optString("orderItemId"));
                workbillItem.put("orderItem", orderItem == null ? null : orderItem.toJSONObject());
                if(!StringUtil.isEmpty(orderItem.getAdId())){
                    AdDesign design = adDesignMapper.selectByPrimaryKey(orderItem.getAdId());
                    workbillItem.put("adDesign", design == null ? null : design.toJSONObject());
                }
            }
        }
        return workbillItems;
    }

    /**
    * 通过id查询
    *
    * @param workbillId
    * @return
    */
    public JSONObject getById(String workbillId) {
        WorkBill workbill = workBillMapper.selectByPrimaryKey(workbillId);
        JSONObject result = null;
        if(workbill != null){
            result = workbill.toJSONObject();
            result.put("workbillItems", getWorkbillItems(workbill.getWorkbillId()));
        }
        return result;
    }

    /**
    * 新增
    *
    * @param workBill
    */
    public void add(WorkBill workBill,ReqBean reqBean) {
        workBill.setStatus(BusConstant.WorkbillStatus.UN_DEAL);
        workBill.setMakeTime(new Date());
        workBill.setModifyTime(workBill.getMakeTime());
        workBillMapper.insert(workBill);
        
        String workbillItemsStr = reqBean.getInfo("workbillItems");
        if(StringUtil.isNotEmpty(workbillItemsStr)){
            JSONArray workbillItems = JSONArray.fromObject(workbillItemsStr);
            if(workbillItems != null){
                for(Object o : workbillItems){
                    JSONObject workbillItem = (JSONObject)o;
                    WorkbillItem item = new WorkbillItem();
                    item.setWorkbillItemId(stringId());
                    item.setWorkbillId(workBill.getWorkbillId());
                    item.setOrderItemId(workbillItem.optString("orderItemId"));
                    
                    item.setOperator(reqBean.getUserId());
                    item.setMakeTime(new Date());
                    item.setModifyTime(new Date());
                    workbillItemMapper.insert(item);
                }
            }
        }
    }
    
    public void send(String workbillId, ReqBean reqBean) {
        if (StringUtil.isEmpty(workbillId)) {
            throw new BusinessException("获取主键失败");
        }
        WorkBill workbill = new WorkBill();
        workbill.setWorkbillId(workbillId);
        workbill.setSender(reqBean.getUserId());
        workbill.setSendTime(new Date());
        workbill.setStatus(BusConstant.WorkbillStatus.DEALING);
        workBillMapper.updateByPrimaryKeySelective(workbill);
        JSONArray items = getWorkbillItems(workbillId);
        Date now = new Date();
        if(items != null){
            String sendStepsStr = reqBean.getInfo("sendSteps");
            JSONArray sendSteps = JSONArray.fromObject(sendStepsStr);
            for(Object o : items){
                JSONObject item = (JSONObject)o;
                String workbillItemId = item.optString("workbillItemId");
                String orderItemId = item.optString("orderItemId");
                for(Object stepObj : sendSteps){
                    JSONObject step = (JSONObject)stepObj;
                    WorkbillTask task = new WorkbillTask();
                    task.setTaskId(stringId());
                    task.setTaskType(step.optString("id"));
                    task.setWorkbillId(workbillId);
                    task.setWorkbillItemId(workbillItemId);
                    task.setOrderItemId(orderItemId);
                    task.setOwner(step.optString("empId"));
                    task.setWorkGroupId(step.optString("groupId"));
                    task.setLimitTime(DateUtil.parse(step.optString("limitTime")));
                    task.setRemark(step.optString("remark"));
                    task.setStatus(BusConstant.Task.STATUS_NOT_COMPLETE);
                    
                    task.setOperator(reqBean.getUserId());
                    task.setMakeTime(now);
                    workbillTaskMapper.insert(task);
                }
            }
        }
    }

    /**
    * 删除
    *
    * @param workbillId
    */
    public void delete(String workbillId) {
        if (StringUtil.isEmpty(workbillId)) {
            throw new BusinessException("获取主键失败");
        }
        //TODO 判断工单是否可删除
        //workBillItemMapper.deleteByWorkbillId(workbillId);
        workBillMapper.deleteByPrimaryKey(workbillId);
    }
    
    public void deleteItem(String workbillItemId){
        //TODO 判断工单明细是否可删除
       // workBillItemMapper.deleteByPrimaryKey(workbillItemId);
    }
    
    /**
     * 通过制作单id查询工作单
     * @param orderId
     * @return
     */
    public List<WorkBill> getWorkBillByOrderId(String orderId){
    	return workBillMapper.selectByOrderId(orderId);
    }
    /**
     * 通过工作单id查询工作单明细
     * @param workBillId
     * @return
     */
//    public List<WorkBillItem> getWorkBillItemByWorkBilllId(String workBillId){
//    	return workBillItemMapper.selectByWorkBilllId(workBillId);
//    }

}